#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QLabel>
#include <QDir>
#include "pluginlist.h"
#include <QSysInfo>
#include <QJsonDocument>
#include "programrun.h"
#include "QJsonArray"
#include "QFileDialog"
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , _JsonFile(0)
{
    ui->setupUi(this);

    _JsonFile = new QFile();

    PlugInList::getInstance()->loadPlugins();

    setWindowTitle("主窗口");
    ui->tableWidget->setSelectionBehavior(QTableWidget:: SelectRows);

    connect(ui->pbadd,      SIGNAL(clicked()),this,SLOT(onDealAddExcel()));
    connect(ui->pddel,      SIGNAL(clicked()),this,SLOT(onDealDelExcel()));
    connect(ui->pbinsert,   SIGNAL(clicked()),this,SLOT(onDealInsertExcel()));
    connect(ui->pvmove_up,  SIGNAL(clicked()),this,SLOT(ondealMoveUpExcel()));
    connect(ui->pvmove_down,SIGNAL(clicked()),this,SLOT(ondealMoveDownExcel()));
    connect(ui->pbcopy,     SIGNAL(clicked()),this,SLOT(ondealCopyExcel()));
    connect(ui->pb_run,     SIGNAL(clicked()),this,SLOT(onDealRun()));

    connect(ui->ac_open,     SIGNAL(triggered()),this,SLOT(ondealactionOpen_Close()));
    connect(ui->ac_save,     SIGNAL(triggered()),this,SLOT(OnDealActionSave()));

    qDebug()<<"buildCpuArchitecture: "   <<QSysInfo::buildCpuArchitecture();
    qDebug()<<"currentCpuArchitecture: " <<QSysInfo::currentCpuArchitecture();
    qDebug()<<"buildAbi: "               <<QSysInfo::buildAbi();
    qDebug()<<"kernelType: "             <<QSysInfo::kernelType();
    qDebug()<<"kernelVersion: "          <<QSysInfo::kernelVersion();
    qDebug()<<"productType: "            <<QSysInfo::productType();
    qDebug()<<"productVersion: "         <<QSysInfo::productVersion();
    qDebug()<<"prettyProductName: "      <<QSysInfo::prettyProductName();
    qDebug()<<"machineHostNam:"          <<QSysInfo::machineHostName();

/*
    QJsonObject test1;
    QJsonObject test2;

    test1["1"] = true;
    test1["2"] = "445";
    test1["3"] = 134;
    test1["4"] = 1.569;

    test2["1"] = false;
    test2["2"] = "456";
    test2["3"] = 710;
    test2["4"] = 1.569;

    QJsonArray tArray;
    tArray.append(test1);
    tArray.append(test2);

    qDebug()<<tArray;

    QJsonDocument jsonDoc(tArray);


    QFile tFile("dsdf.json");
    tFile.open(QIODevice::ReadWrite);

   tFile.write(jsonDoc.toJson());
    tFile.close();
*/
/*
    QJsonParseError jsonError;

    QFile tFile("dsdf.json");
    tFile.open(QIODevice::ReadWrite);

    QByteArray jsonba = tFile.readAll();
    QJsonDocument document = QJsonDocument::fromJson(jsonba,&jsonError);

    if (document.isArray())
    {
        //QJsonArray jsonArray = document.array();
        qDebug() << "JSON数组:" << document;
    } else {
        qDebug() << "无效的JSON文档";
    }

    tFile.close();
*/

}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::Addnewexcel(quint32 rownums)
{
    ui->tableWidget->insertRow(rownums);

    // 第 0 列
    QCheckBox *pbox = new QCheckBox();
    pbox->setText("");
    pbox->setChecked(true);
    pbox->setStyleSheet("QCheckBox::text { color: transparent; }"); // 隐藏文本
    ui->tableWidget->setCellWidget(rownums, 0, pbox);

    //第1列
    QLabel *pLabel = new QLabel();
    pLabel->setAlignment(Qt::AlignHCenter); // 设置文本水平居中
    pLabel->setAlignment(Qt::AlignCenter); // 设置文本居中
    pLabel->setStyleSheet("QLabel { background-color:green;}");
    pLabel->setText("未配置");
    ui->tableWidget->setCellWidget(rownums,1, pLabel);

    //第2列 标识
    QTableWidgetItem *item2 = new QTableWidgetItem();
    ui->tableWidget->setItem(rownums,2,item2);

    //第3列
    MainWindowCombox *pComBox = new MainWindowCombox();
    connect(pComBox,      SIGNAL(sigGetConfig(QJsonObject)),this,SLOT(onDealGetConfigJson(QJsonObject)));
    for(uint32_t i = 0;i < PlugInList::getInstance()->GetPlugInNum();i++)
    {
        PlugIn_Base * pPlugIn = PlugInList::getInstance()->GetPlug(i);
        pComBox->addItem(pPlugIn->GetLable());
    }
    ui->tableWidget->setCellWidget(rownums,3, pComBox);

    //第4列
    QTableWidgetItem *item4 = new QTableWidgetItem();
    item4->setFlags(Qt::ItemIsEnabled); // 设置单元格为不可编辑，但可交互
    ui->tableWidget->setItem(rownums,4,item4);

    //第5列 下限值
    QTableWidgetItem *item5 = new QTableWidgetItem();
    ui->tableWidget->setItem(rownums,5,item5);

    //第6列 上限值
    QTableWidgetItem *item6 = new QTableWidgetItem();
    ui->tableWidget->setItem(rownums,6,item6);

    //第7列 单位
    QTableWidgetItem *item7 = new QTableWidgetItem();
    ui->tableWidget->setItem(rownums,7,item7);

    for(uint32_t i = 0;i < ui->tableWidget->columnCount();i++)
    {
        QTableWidgetItem *item = ui->tableWidget->item(rownums,i);
        if(item)
             item->setTextAlignment(Qt::AlignCenter);//文本居中
    }
}

void MainWindow::Copyexcel(quint32 baserow,quint32 tarrow)
{
    // 第 0 列
    QCheckBox *pBaseCheckBox   = (QCheckBox *)ui->tableWidget->cellWidget(baserow,0);
    QCheckBox *pTarrowCheckBox = (QCheckBox *)ui->tableWidget->cellWidget(tarrow,0);
    pTarrowCheckBox->setCheckState(pBaseCheckBox->checkState());

    //第1列
    QLabel *pBaseLabel   = (QLabel *)ui->tableWidget->cellWidget(baserow,1);
    QLabel *pTarrowLabel = (QLabel *)ui->tableWidget->cellWidget(tarrow,1);
    pTarrowLabel->setText(pBaseLabel->text());

    //第2列 标识
    QTableWidgetItem *pbaseItemrow2   = ui->tableWidget->item(baserow,2);
    QTableWidgetItem *ptarItemrow2   = ui->tableWidget->item(tarrow,2);
    ptarItemrow2->setText(pbaseItemrow2->text());

    //第3列
    MainWindowCombox *pBaseCombox =  (MainWindowCombox *)ui->tableWidget->cellWidget(baserow,3);
    MainWindowCombox *pTarCombox  =  (MainWindowCombox *)ui->tableWidget->cellWidget(tarrow,3);
    pTarCombox->setCurrentIndex(pBaseCombox->currentIndex());


    //第4列
    QTableWidgetItem *pbaseItemrow4   = ui->tableWidget->item(baserow,4);
    QTableWidgetItem *ptarItemrow4   = ui->tableWidget->item(tarrow,4);
    ptarItemrow4->setText(pbaseItemrow4->text());

    //第5列
    QTableWidgetItem *pbaseItemrow5   = ui->tableWidget->item(baserow,5);
    QTableWidgetItem *ptarItemrow5   = ui->tableWidget->item(tarrow,5);
    ptarItemrow5->setText(pbaseItemrow5->text());

    //第6列
    QTableWidgetItem *pbaseItemrow6   = ui->tableWidget->item(baserow,6);
    QTableWidgetItem *ptarItemrow6   = ui->tableWidget->item(tarrow,6);
    ptarItemrow6->setText(pbaseItemrow6->text());

    //第7列
    QTableWidgetItem *pbaseItemrow7   = ui->tableWidget->item(baserow,7);
    QTableWidgetItem *ptarItemrow7   = ui->tableWidget->item(tarrow,7);
    ptarItemrow7->setText(pbaseItemrow7->text());
}

uint8_t MainWindow::Analysejsonfile(QString path)
{
    _JsonFile->setFileName(path);
    bool ret = _JsonFile->open(QIODevice::ReadWrite);
    if(!ret)
    {
        QMessageBox::warning(NULL, "Warning", "文件打开失败");
        _JsonFile->close();
        return 0;
    }
    QByteArray jsonba = _JsonFile->readAll();
    QJsonDocument document = QJsonDocument::fromJson(jsonba);

    if (document.isArray())
    {
        qDebug()<<"isArray";
        //先清空
        uint32_t RowCount =  ui->tableWidget->rowCount();
        for(uint32_t i = 0;i < RowCount;i++)
        {
            ondealRemoverow(0);
        }
        QJsonArray jsonArray = document.array();

        qDebug()<<"jsonArraysize"<<jsonArray.size();
        //在增加
        for(uint32_t i = 0;i < jsonArray.size(); i++)
        {
            onDealAddExcel();
            QJsonObject jsonObj = jsonArray[i].toObject();
            qDebug()<<__func__<<":"<<jsonObj;
            InitTableRow(ui->tableWidget->rowCount() - 1,jsonObj);
        }
    }
    else
    {
        QMessageBox::warning(NULL, "Warning", "json文件解析打开失败");
        _JsonFile->close();
        return 0;
    }
    _JsonFile->close();
    return 1;
}

void MainWindow::RefleshEditTableWidget(QJsonArray array)
{
#if 0
    for(uint32_t i = 0;i < array.size(); i++)
    {
        QJsonValue jsonvalue = array.at(i);


        // 第 0 列
        QCheckBox *pCheckBox = (QCheckBox *)ui->tableWidget->cellWidget(i, 0);
        obj["type"] = pCheckBox->checkState();

        //第1列
        QLabel *pLabel =  (QLabel *)ui->tableWidget->cellWidget(i, 1);
        obj["sta"] = pLabel->text();

        //第2列 标识
        QString UserFlag = ui->tableWidget->item(i,2)->text();
        obj["UserFlag"] = UserFlag;

        //第3列

        MainWindowCombox *pCombox =  ( MainWindowCombox *)ui->tableWidget->cellWidget(i,3);
        QString QStrcmd = pCombox->currentText();
        obj["Cmd"] = QStrcmd;

        //第4列
        MainWindowCombox *pDetail =  ( MainWindowCombox *)ui->tableWidget->cellWidget(i,3);
        QJsonObject JsonDetail = pDetail->GetJson();
        obj["CmdDetail"] = JsonDetail;

        //第5列 下限值
        QString Low = ui->tableWidget->item(i,5)->text();
        obj["under"] = Low;

        //第6列 上限值
        QString upper = ui->tableWidget->item(i,6)->text();
        obj["upper"] = upper;

        //第7列 单位
        QString unit = ui->tableWidget->item(i,7)->text();
        obj["unit"] = unit;

    }
#endif
}

void MainWindow::InitTableRow(int row,QJsonObject json)
{
    // 第 0 列
    QCheckBox *pCheckBox = (QCheckBox *)ui->tableWidget->cellWidget(row, 0);
    if(json["type"].toBool())
        pCheckBox->setCheckState(Qt::Checked);
    else
        pCheckBox->setCheckState(Qt::Unchecked);

    //第1列
    QLabel *pLabel =  (QLabel *)ui->tableWidget->cellWidget(row, 1);
    pLabel->setText(json["sta"].toString());

    //第2列 标识
    ui->tableWidget->item(row,2)->setText(json["UserFlag"].toString());

    //第3列
    MainWindowCombox *pCombox =  ( MainWindowCombox *)ui->tableWidget->cellWidget(row,3);
    pCombox->setCurrentText(json["Cmd"].toString());

    //第4列
    qDebug()<<json["CmdDetail"];
    QJsonObject CmdDetailJsonObj = json["CmdDetail"].toObject();
    pCombox->SetJson(CmdDetailJsonObj);

    if(CmdDetailJsonObj.isEmpty() == 0)
    {
        QString strRet;
        QJsonDocument doc(CmdDetailJsonObj);
        strRet = QString(doc.toJson(QJsonDocument::Compact));
        ui->tableWidget->item(row,4)->setText(strRet);
    }

    //第5列 下限值
    ui->tableWidget->item(row,5)->setText(json["under"].toString());

    //第6列 上限值
   ui->tableWidget->item(row,6)->setText(json["upper"].toString());

    //第7列 单位
    ui->tableWidget->item(row,7)->setText(json["unit"] .toString());
}

void MainWindow::ondealRemoverow(quint32 row)
{
    if (row >= 0)
    {
        // 第 0 列
        delete ui->tableWidget->cellWidget(row, 0);

        //第1列
        delete ui->tableWidget->cellWidget(row,1);

        //第2列 标识
        delete ui->tableWidget->item(row,2);

        //第3列
        delete ui->tableWidget->cellWidget(row,3);

        //第4列
        delete ui->tableWidget->item(row,4);

        //第5列 下限值
        delete ui->tableWidget->item(row,5);

        //第6列 上限值
        delete ui->tableWidget->item(row,6);

        //第7列 单位
        delete ui->tableWidget->item(row,7);

        ui->tableWidget->removeRow(row); // 删除行
        ui->tableWidget->setCurrentItem(NULL);
    }
}
void MainWindow::onDealAddExcel(void)
{
    quint32 rownums = ui->tableWidget->rowCount();
    Addnewexcel(rownums);
}

void MainWindow::onDealDelExcel(void)//删除一行
{
    int row = ui->tableWidget->currentRow(); // 获取当前选中行的索引
    ondealRemoverow(row);
}

void MainWindow::onDealInsertExcel(void)//插入一行
{
    int row = ui->tableWidget->currentRow(); // 获取当前选中行的索引
    if (row >= 0) {
        Addnewexcel(row+1);
        ui->tableWidget->setCurrentItem(NULL);
    }
}

void MainWindow::ondealMoveUpExcel(void)/*向上移动一行 */
{
    int currentRow = ui->tableWidget->currentRow(); // 获取当前选中行的索引
    qDebug()<<"currentRow"<<currentRow;
    if(currentRow == 0)
        return ;
    if(currentRow < 0)
        return ;
    Addnewexcel(currentRow - 1);
    Copyexcel(currentRow+1,currentRow - 1);
    ondealRemoverow(currentRow + 1);
}

void MainWindow::ondealMoveDownExcel(void)//向下移动一行
{
    int currentRow = ui->tableWidget->currentRow(); // 获取当前选中行的索引
    qDebug()<<"currentRow"<<currentRow;
    qDebug()<<"ui->tableWidget->rowCount()"<<ui->tableWidget->rowCount();
    if(currentRow+1 >=  ui->tableWidget->rowCount())
        return ;
    if(currentRow < 0)
        return ;
    Addnewexcel(currentRow +2);
    Copyexcel(currentRow,currentRow + 2);

    ondealRemoverow(currentRow);

}

void MainWindow::ondealCopyExcel(void)  //复制excel
{
    int row = ui->tableWidget->currentRow(); // 获取当前选中行的索引
    if(row < 0)
        return ;
    Addnewexcel(row+1);
    Copyexcel(row,row + 1);
    ui->tableWidget->setCurrentItem(NULL);
}

void MainWindow::onDealGetConfigJson(QJsonObject json)
{
    QString strRet;
    QJsonDocument doc(json);
    strRet = QString(doc.toJson(QJsonDocument::Compact));
    qDebug()<<__func__<<": "<<strRet;

     MainWindowCombox *pSender  = (MainWindowCombox *)sender();
    for(uint32_t i = 0;i < ui->tableWidget->rowCount();i++)
    {
         MainWindowCombox *pWid = (MainWindowCombox *)ui->tableWidget->cellWidget(i,3);
         if(pWid == pSender)
         {
             ui->tableWidget->item(i,4)->setText(strRet);
            return ;
         }
    }
}

void MainWindow::onDealRun(void)
{
    ProGramRun *pRun = new ProGramRun();

    for(uint32_t i = 0;i < ui->tableWidget->rowCount();i++)
    {
        QCheckBox *pCheckBox = ( QCheckBox *)ui->tableWidget->cellWidget(i,0);
        if(pCheckBox->checkState() == Qt::Unchecked)
            continue;

        T_program_Unit tUnit = {0};

        tUnit.StrFlag     = ui->tableWidget->item(i,2)->text();

        MainWindowCombox *pComBox = ( MainWindowCombox *)ui->tableWidget->cellWidget(i,3);
        tUnit.StrCmd = pComBox->currentText();

        tUnit.JsonObj = pComBox->GetJson();
        tUnit.StrDetail =  ui->tableWidget->item(i,4)->text();

        tUnit.StrLevelLower =  ui->tableWidget->item(i,5)->text();;
        tUnit.StrLevelUpper =  ui->tableWidget->item(i,6)->text();;
        tUnit.StrUnit       =  ui->tableWidget->item(i,7)->text();;


        pRun->ProGramRum_Add(&tUnit);
    }

    pRun->show();

}



void MainWindow::ondealactionOpen_Close(void)
{
    uint8_t ret = 0;
    if(ui->ac_open->text() == "打开")
    {
        while(1)
        {
            QString fileName = QFileDialog::getOpenFileName(this,tr("选择脚本文件"),"",tr("*.json")); // 文件过滤器
            if(fileName.isEmpty())
            {
                ret = 0;
                break;
            }
            else
            {
                if(Analysejsonfile(fileName))//解析json 文件
                {
                    ret = 1;
                    break;
                }
            }
        }
        if(ret)
        {
            ui->ac_open ->setText("关闭");
        }
    }
    else
    {
        uint32_t RowCount =  ui->tableWidget->rowCount();
        for(uint32_t i = 0;i < RowCount;i++)
        {
            ondealRemoverow(0);
        }
        ui->ac_open ->setText("打开");
    }
}
void MainWindow::OnDealActionSave(void)
{

    QJsonArray Array;
    for(uint32_t i = 0 ;i < ui->tableWidget->rowCount() ;i++)
    {
        QJsonObject obj ;

        // 第 0 列
        QCheckBox *pCheckBox = (QCheckBox *)ui->tableWidget->cellWidget(i, 0);
        obj["type"] = pCheckBox->checkState() == Qt::Checked?true:false;

        //第1列
        QLabel *pLabel =  (QLabel *)ui->tableWidget->cellWidget(i, 1);
        obj["sta"] = pLabel->text();

        //第2列 标识
        QString UserFlag = ui->tableWidget->item(i,2)->text();
        obj["UserFlag"] = UserFlag;

        //第3列
        MainWindowCombox *pCombox =  ( MainWindowCombox *)ui->tableWidget->cellWidget(i,3);
        QString QStrcmd = pCombox->currentText();
        obj["Cmd"] = QStrcmd;


        //第4列
        MainWindowCombox *pDetail =  ( MainWindowCombox *)ui->tableWidget->cellWidget(i,3);
        QJsonObject JsonDetail = pDetail->GetJson();
        obj["CmdDetail"] = JsonDetail;

        //第5列 下限值
        QString Low = ui->tableWidget->item(i,5)->text();
        obj["under"] = Low;

        //第6列 上限值
        QString upper = ui->tableWidget->item(i,6)->text();
        obj["upper"] = upper;

        //第7列 单位
        QString unit = ui->tableWidget->item(i,7)->text();
        obj["unit"] = unit;

        Array.append(obj);

        qDebug()<<obj;
    }
    qDebug()<<Array;
    QJsonDocument jsonDoc(Array);
    if(ui->ac_open->text() == "关闭")//有文件
    {
        bool ret = _JsonFile->open(QIODevice::ReadWrite);
        if(!ret)
        {
            QMessageBox::warning(NULL, "Warning", "文件打开失败");
            _JsonFile->close();
            return ;
        }
        _JsonFile->resize(0);
        _JsonFile->write(jsonDoc.toJson());
        _JsonFile->close();
    }
    else
    {
        QString fileName = QFileDialog::getSaveFileName(nullptr,
                                                        "保存文件到",
                                                        "",
                                                        "*.json");

        if (!fileName.isEmpty())
        {
            qDebug()<<fileName;



            QFile tFile(fileName);
            tFile.open(QIODevice::ReadWrite);

            tFile.write(jsonDoc.toJson());
            tFile.close();
        }
    }

}

MainWindowCombox::MainWindowCombox(QWidget *parent )
:QComboBox(parent)
{

}

QJsonObject MainWindowCombox::GetJson(void)
{
    return _Json;
}

void MainWindowCombox::SetJson(QJsonObject json)
{
    _Json = json;
}

void MainWindowCombox::contextMenuEvent(QContextMenuEvent *event) // 处理上下文菜单事件
{
    QMenu menu(this);

    // 添加一些动作到菜单
    QAction *action1 = menu.addAction("编辑指令");
    QAction *action2 = menu.addAction("保留...");

    connect(action1, SIGNAL(triggered()), this, SLOT(onCustomAction1()));
    connect(action2, SIGNAL(triggered()), this, SLOT(onCustomAction2()));
    // 在鼠标位置显示菜单
    menu.exec(QCursor::pos());
}

void MainWindowCombox::onCustomAction1(void)
{
    qDebug()<<__func__;
    for(uint32_t i = 0;i< PlugInList::getInstance()->GetPlugInNum();i++)
    {
        if( PlugInList::getInstance()->GetPlug(i)->GetLable() == this->currentText())
        {
            QJsonObject tmpjson = PlugInList::getInstance()->GetPlug(i)->Config(_Json);
            if(!tmpjson.isEmpty() )
            {
               _Json =tmpjson;
               emit  sigGetConfig(_Json);
            }
            return ;
        }
    }
}
void MainWindowCombox::onCustomAction2(void)
{
   qDebug()<<__func__;
}
